package com.pitaya.winwine.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.pitaya.framework.common.Constants;
import com.pitaya.framework.common.ErrorInfo;
import com.pitaya.winwine.domain.Taste;
import com.pitaya.winwine.domain.User;
import com.pitaya.winwine.domain.Vintry;
import com.pitaya.winwine.domain.VintryLog;
import com.pitaya.winwine.domain.Wine;
import com.pitaya.winwine.domain.WineAdvice;
import com.pitaya.winwine.repository.DictRepository;
import com.pitaya.winwine.repository.TasteRepository;
import com.pitaya.winwine.repository.VintryLogRepository;
import com.pitaya.winwine.repository.VintryRepository;
import com.pitaya.winwine.repository.WineAdviceRepository;
import com.pitaya.winwine.repository.WineRepository;
import com.pitaya.winwine.repository.spec.VintrySpec;
import com.pitaya.winwine.service.VintryService;
import com.pitaya.winwine.service.WineService;

@Controller
@RequestMapping("/vintry")
public class VintryAction {

	@Autowired
	private DictRepository dictRepository;
	
	@Autowired
	private WineService wineService;
	
	@Autowired
	private WineRepository wineRepository;
	
	@Autowired
	private VintryService vintryService;
	
	@Autowired
	private VintryRepository vintryRepository;
	
	@Autowired
	private VintryLogRepository vintryLogRepository;
	
	@Autowired
	private WineAdviceRepository wineAdviceRepository;
	
	@Autowired
	private TasteRepository tasteRepository;

	// 创建酒管家
	@RequestMapping(value = "/wine/create")
	public ModelAndView toCreate(Wine wine) {
		Map model = new HashMap();
		model.put("capacityList", dictRepository.findByPid(Constants.DICT_CAPACITY));
		model.put("countryList", dictRepository.findByPid(Constants.DICT_COUNTRY));
		model.put("typeList", dictRepository.findByPid(Constants.DICT_WINE));
		wine.setCapacity(Wine.DEFAULT_CAPACITY);
		model.put("wine", wine);
		return new ModelAndView("vintry/wine_create", model);
	}
	@RequestMapping(value = "/create" , method = RequestMethod.POST)
	public ModelAndView doCreate(HttpServletRequest request, HttpSession session, Vintry vintry,
			@RequestParam("pic") MultipartFile file) {
		
		User user = (User)session.getAttribute("user");
		vintry.setUser(user);
		vintry = vintryService.create(vintry, file);
		ErrorInfo errorInfo = vintry.getErrorInfo();
		Map model = new HashMap();
		
		if(errorInfo == null) {
			return new ModelAndView("redirect:/");
		} else if(errorInfo.equals(ErrorInfo.INVALID_UPLOAD_FORMAT) || errorInfo.equals(ErrorInfo.INVALID_UPLOAD_SIZE)) {
			model.put("countryList", dictRepository.findByPid(Constants.DICT_COUNTRY));
	    	model.put("typeList", dictRepository.findByPid(Constants.DICT_WINE));
	    	model.put("vintry", vintry.getWine());
	    	model.put("errorMsg", errorInfo.getMsg());
	    	return new ModelAndView("vintry/create");
		}else if(errorInfo.equals(ErrorInfo.ISEXIST_WINE)) {
			model.put("vintry", vintry);
	    	return new ModelAndView("vintry/wine_confirm", model);
		}else {
			return new ModelAndView("redirect:/vintry/detail/vintry/{id}", "id", vintry.getId());
		}
	}
	
	// 酒管家详细信息
	@RequestMapping("/detail/{tabName}/{id}")
	public ModelAndView vintryDetail(HttpSession session, @PathVariable("tabName") String tabName,
			@PathVariable("id") Integer id) {
	    Integer userId = ((User)session.getAttribute("user")).getId();
	    Map model = new HashMap();
	    model.put("tabName", tabName);
	    model.put("vintry", vintryRepository.findByIdAndUserId(id, userId));
	    return new ModelAndView("vintry/vintry_detail", model);
	}
	@RequestMapping("/save")
	public ModelAndView save(HttpSession session, Vintry vintry) {
	    vintryService.update(vintry);
	    return new ModelAndView("redirect:/vintry/detail/wine/{id}", "id", vintry.getId());
	}
	@RequestMapping("/log/add")
	public String addLog(HttpSession session, VintryLog vintryLog) {
		User user = (User)session.getAttribute("user");
		vintryLog.setUser(user);
		vintryService.addVintryLog(vintryLog);
		return "redirect:/vintry";
	}
	
	//红酒纠错
	@RequestMapping("/wine/advice/{wineId}")
	public ModelAndView wineAdviceList(@PathVariable("wineId")Integer wineId) {
	    return new ModelAndView("vintry/wine_advice", "wineId", wineId);
	}
	@RequestMapping(value = "/wine/advice/save", method = RequestMethod.POST)
	public ModelAndView wineAdviceList(HttpSession session, WineAdvice wineAdvice) {
		User user = (User)session.getAttribute("user");
		wineAdvice.setUser(user);
		wineAdvice.setCreateTime(new Date());
		wineAdvice.setWine(wineRepository.findOne(wineAdvice.getWine().getId()));
		Map model = new HashMap();
		model.put("wineId", wineAdviceRepository.save(wineAdvice).getWine().getId());
		model.put("msg", "我们会仔细核对您的修改建议");
	    return new ModelAndView("vintry/wine_advice", model);
	}

	//我的藏酒
	@RequestMapping
	public ModelAndView vintrylist(HttpSession session, Integer index, Integer sortType, String sortField) {
		if(index == null) index = 0;
		if(sortType == null) sortType = 1;
		if(StringUtils.isEmpty(sortField)) sortField = "editTime";
		User user = (User) session.getAttribute("user");		
		Page<Vintry> page = vintryRepository.findByUserId(user.getId(),
				new PageRequest(index, 10, new Sort(sortType==0?Direction.ASC:Direction.DESC, sortField)));
		Map model = new HashMap();
		model.put("page", page);
		model.put("index", index);
		model.put("sortType", sortType);
		model.put("sortField", sortField);
		return new ModelAndView("vintry/vintry_list", model);
	}
	//导出EXCEL
	@RequestMapping({"/export"})
	public void exportVintory(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
	    vintryService.export(session, request, response);
	}
	
	//适饮期提醒
	@RequestMapping("/drinkingPeriod/list")
	public ModelAndView wineUserList(HttpSession session, Integer index, Integer sortType, String sortField) {
		if(index == null) index = 0;
		if(sortType == null) sortType = 1;
		if(StringUtils.isEmpty(sortField)) sortField = "editTime";
	    User user = (User)session.getAttribute("user");
	    Page<Vintry> page = vintryRepository.findAll(VintrySpec.findDrinkingPeriodList(user.getId()),
	    		new PageRequest(index, 10, new Sort(sortType==0?Direction.ASC:Direction.DESC, sortField)));
	    Map model = new HashMap();
		model.put("page", page);
		model.put("index", index);
		model.put("sortType", sortType);
		model.put("sortField", sortField);
	    return new ModelAndView("vintry/drinkingPeriod_list", model);
	}
	
	//餐饮搭配
	@RequestMapping("/food")
	public String food() {
		return "vintry/food_index";
	}
	@RequestMapping("/food/list")
	public ModelAndView foodList(HttpSession session, Vintry vintry, Integer index, Integer sortType, String sortField) {
		if(index == null) index = 0;
		if(sortType == null) sortType = 1;
		if(StringUtils.isEmpty(sortField)) sortField = "editTime";
	    User user = (User)session.getAttribute("user");
	    vintry.setUser(user);
	    Page<Vintry> page = vintryRepository.findAll(VintrySpec.findFoodList(vintry), 
	    		new PageRequest(index, 10, new Sort(sortType==0?Direction.ASC:Direction.DESC, sortField)));
	    Map model = new HashMap();
		model.put("page", page);
		model.put("index", index);
		model.put("sortType", sortType);
		model.put("sortField", sortField);
	    model.put("countryList", dictRepository.findByPid(Constants.DICT_COUNTRY));
	    model.put("typeList", dictRepository.findByPid(Constants.DICT_WINE));
	    return new ModelAndView("vintry/food_list", model);
	}
	
	//品酒日志
	@RequestMapping("/taste/list")
	public ModelAndView tastingList(HttpSession session, Integer index) {
		if(index == null) index = 0;
		Integer userId = ((User)session.getAttribute("user")).getId();
		Page page = tasteRepository.findByUserId(userId,
	    		new PageRequest(index, 5, new Sort(Sort.Direction.DESC, "createTime")));
		Map model = new HashMap();
		model.put("page", page);
		model.put("index", index);
	    return new ModelAndView("/vintry/taste_list", model);
	}
	@RequestMapping(value = "/taste/create", method = RequestMethod.GET)
	public String tastingDetail() {
	    return "vintry/taste_create";
	}
	@RequestMapping(value = "/taste/create", method = RequestMethod.POST)
	public String tastingSave(HttpSession session, Taste taste) {
		User user = (User)session.getAttribute("user");
	    taste.setUser(user);
	    taste.setCreateTime(new Date());
	    tasteRepository.save(taste);
	    return "redirect:/vintry/taste/list";
	}
	
	//藏酒记录
	@RequestMapping("/log/list")
	public ModelAndView logList(HttpSession session, Integer index) {
		if(index == null) index = 0;
	    Integer userId = ((User)session.getAttribute("user")).getId();
	    Map model = new HashMap();
	    model.put("page", vintryLogRepository.findByUserId(userId,
	    		new PageRequest(index, 30, new Sort(Sort.Direction.DESC, "editTime"))));
	    model.put("index", index);
	    return new ModelAndView("vintry/log_list", model);
	}
	
	//左侧菜单
	@RequestMapping("/menu")
	public ModelAndView menu(HttpSession session) {
		User user = (User)session.getAttribute("user");
		long drinkingPeriodCount = vintryRepository.count(VintrySpec.findDrinkingPeriodList(user.getId()));
		return new ModelAndView("vintry/menu", "drinkingPeriodCount", drinkingPeriodCount);
	}

}
